<template>

  <!-- 100vh:元素高度为屏幕可见高度 -->
  <div style="height:100vh;
              background-image: linear-gradient(135deg,#1355F3,#3C82F5);
              overflow: auto;">
    <el-container style="padding: 30px; margin:0 auto;width: 1600px">
      <el-header>
        <el-row>
          <el-col :span="3">
            <img src="/imgs/login/logo.png" style="height: 50px;">
          </el-col>
          <el-col :span="1">
            <img src="/imgs/login/auto.png" style="height: 50px;">
          </el-col>
          <el-col :span="1">
            <img src="/imgs/login/verticalLine.png" style="height: 50px;">
          </el-col>
          <el-col :span="19">
            <span style="color: #fff;font-weight: bold;font-size: 30px">智慧车辆运营管理系统</span>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <el-row>
          <el-col :span="16">
            <img src="/imgs/login/bg.png" style="width: 100%;margin-top: 60px">
          </el-col>
          <el-col :span="8">
            <el-card style="margin-top: 80px;width:420px;border-radius: 25px">

              <h3 style="text-align: center">用户登录</h3>
              <div style="display:flex;align-items: center;justify-content: center"><!--align-items: center：垂直居中；justify-content: center:横向居中-->
                <el-form :model="user" :rules="rules" ref="formRef"  label-position="top" style="width: 80%;">
                  <el-form-item prop="username" label="用户名">
                    <el-input v-model="user.username" placeholder="请输入用户名"></el-input>
                  </el-form-item>
                  <el-form-item prop="password" label="密码">
                    <el-input v-model="user.password" placeholder="请输入密码"></el-input>
                  </el-form-item>
                  <!--      验证码          -->
                  <el-form-item prop="validateCode" label="验证码">
                    <el-input v-model="user.validateCode" placeholder="请输入验证码" style="width: 40%;"></el-input>
                    <ValidateCode ref="ref_validateCode" @change="changeCode" style="margin-left: 50px;height: 32px"/>
                  </el-form-item>

                  <el-form-item>
                    <el-button @click="login" type="primary" style="width: 100%">登录</el-button>
                  </el-form-item>
                  <div style="display: flex;">
                    <div style="flex:1">还没有账号？请<span style="color: #296CF4FF;cursor:pointer">注册</span></div>
                    <div style="flex:1;text-align:right;"><span style="color: #296CF4FF;cursor:pointer">忘记密码</span></div>
                  </div>
                </el-form>
              </div>
              <div style="text-align: center;color:#666;font-size: 14px;padding: 10px 0">
                (体验账号：tom 密码：123456)

              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>

</template>
<script setup>
import {ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";
import ValidateCode from "@/components/ValidateCode.vue";

const ref_validateCode = ref(null)
let genderCode = ''
const changeCode = (value)=>{
 genderCode = value
}
const user = ref({
  username: '',
  password: '',
  validateCode:''
})
const formRef = ref(null)
const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9]{3,20}$/, message: '用户名必须是3-20位的字母或数字', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9]{6,20}$/, message: '密码必须是6-20位的字母或数字', trigger: 'blur'}
  ],
  validateCode:[
    {required:true,message:'请输入验证码',trigger:'blur'},
  ]
}
const validateUsername = () => {
  if (!user.value.username.match(/^[a-zA-Z0-9]{3,20}$/)) {
    ElMessage.error('用户名必须是3-20位的字母或数字');
  }
};
const validatePassword = () => {
  if (!user.value.password.match(/^[a-zA-Z0-9]{6,20}$/)) {
    ElMessage.error('密码必须是6-20位的字母或数字');
  }
};
const login = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.error('请检查输入的信息')
    }else{
        if(user.value.validateCode.toUpperCase() === genderCode){
          ElMessage.success('验证成功')
          console.log(user.value);
          let data = qs.stringify(user.value)
          //给后端发送登录请求，需要借助axios工具，（使用之前需要安装并导入）
          /*异步操作*/
          axios.post(BASE_URL + '/v1/user/login', data)
              .then((response) => {
                //发送请求后，服务器处理完毕会给客户端响应结果，前端需要在回调函数中处理这个响应结果
                //response是响应对象，我们可以从响应对象的data属性获取响应的数据
                console.log(response);
                console.log(response.data)
                console.log(response.data.data)
                //根据响应做出判断
                //===严格相等；==宽松相等（只比较值）
                if (response.data.code === 2000) {
                  /*不同网站之间的LocalStorage数据是完全隔离的。这意味着每个域名（甚至不同的子域名）都有独立的LocalStorage空间。具体来说：
        同源策略：浏览器的同源策略（Same-origin policy）确保了不同域名下的LocalStorage数据不会互相干扰。只有在同一域名下的页面才能访问该域名下的LocalStorage数据。
        隔离机制：
        如果网站A（例如 example.com）设置了一个键 key1，那么这个键只能被 example.com 下的页面访问。
        网站B（例如 another-example.com）即使设置了相同的键 key1，也不会影响到网站A的LocalStorage数据。*/
                  /*localStorage只能存储字符串类型的键值对*/
                  localStorage.setItem('user', JSON.stringify(response.data.data))
                  ElMessage.success('登陆成功！')
                  router.push('/');
                } else {
                  ElMessage.error('登陆失败！')
                  user.value = {
                    username: '',
                    password: ''
                  }
                }
              })
        }else{
          ElMessage.error('验证码输入错误')
          ref_validateCode.value.draw();//刷新验证码
        }
    }
  })
}

</script>


<style scoped>

</style>